package com.joker.airoleplayplatformback.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 音频格式转换工具类
 * 用于处理不同格式的音频文件转换
 *
 * @author feixiang.li
 * @since 2025-09-27
 */
@Slf4j
public class AudioFormatConverter {

    /**
     * 将webm格式转换为wav格式
     * 注意：这是一个简化的实现，实际项目中可能需要使用FFmpeg等工具
     */
    public static String convertWebmToWav(String webmFilePath) {
        try {
            File webmFile = new File(webmFilePath);
            if (!webmFile.exists()) {
                log.error("源文件不存在: {}", webmFilePath);
                return null;
            }

            // 生成wav文件路径
            String wavFilePath = webmFilePath.replace(".webm", ".wav");
            
            // 读取webm文件内容
            byte[] webmData = Files.readAllBytes(webmFile.toPath());
            
            // 创建简单的WAV文件头
            byte[] wavHeader = createWavHeader(webmData.length);
            
            // 合并头部和数据
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            baos.write(wavHeader);
            baos.write(webmData);
            
            // 写入wav文件
            Files.write(Paths.get(wavFilePath), baos.toByteArray());
            
            log.info("音频格式转换完成: {} -> {}", webmFilePath, wavFilePath);
            return wavFilePath;
            
        } catch (Exception e) {
            log.error("音频格式转换失败", e);
            return null;
        }
    }

    /**
     * 创建简单的WAV文件头
     * 注意：这是一个简化的实现，实际项目中应该使用专业的音频处理库
     */
    private static byte[] createWavHeader(int dataLength) {
        ByteArrayOutputStream header = new ByteArrayOutputStream();
        try {
            // RIFF header
            header.write("RIFF".getBytes());
            header.write(intToLittleEndian(36 + dataLength)); // 文件大小
            header.write("WAVE".getBytes());
            
            // fmt chunk
            header.write("fmt ".getBytes());
            header.write(intToLittleEndian(16)); // fmt chunk size
            header.write(shortToLittleEndian((short) 1)); // audio format (PCM)
            header.write(shortToLittleEndian((short) 1)); // number of channels
            header.write(intToLittleEndian(16000)); // sample rate
            header.write(intToLittleEndian(32000)); // byte rate
            header.write(shortToLittleEndian((short) 2)); // block align
            header.write(shortToLittleEndian((short) 16)); // bits per sample
            
            // data chunk
            header.write("data".getBytes());
            header.write(intToLittleEndian(dataLength)); // data size
            
        } catch (IOException e) {
            log.error("创建WAV头部失败", e);
        }
        
        return header.toByteArray();
    }

    /**
     * 将int转换为小端序字节数组
     */
    private static byte[] intToLittleEndian(int value) {
        return new byte[]{
            (byte) (value & 0xff),
            (byte) ((value >> 8) & 0xff),
            (byte) ((value >> 16) & 0xff),
            (byte) ((value >> 24) & 0xff)
        };
    }

    /**
     * 将short转换为小端序字节数组
     */
    private static byte[] shortToLittleEndian(short value) {
        return new byte[]{
            (byte) (value & 0xff),
            (byte) ((value >> 8) & 0xff)
        };
    }

    /**
     * 检查文件是否为有效的音频文件
     */
    public static boolean isValidAudioFile(String filePath) {
        try {
            File file = new File(filePath);
            if (!file.exists() || file.length() == 0) {
                return false;
            }

            // 读取文件头
            byte[] header = new byte[12];
            try (FileInputStream fis = new FileInputStream(file)) {
                int bytesRead = fis.read(header);
                if (bytesRead < 12) {
                    return false;
                }
            }

            // 检查是否为WAV或WebM文件
            String headerStr = new String(header, 0, 4);
            if ("RIFF".equals(headerStr)) {
                String format = new String(header, 8, 4);
                return "WAVE".equals(format) || "WEBM".equals(format);
            }

            return false;
            
        } catch (Exception e) {
            log.error("检查音频文件失败", e);
            return false;
        }
    }

    /**
     * 获取音频文件信息
     */
    public static AudioFileInfo getAudioFileInfo(String filePath) {
        try {
            File file = new File(filePath);
            if (!file.exists()) {
                return null;
            }

            AudioFileInfo info = new AudioFileInfo();
            info.setFilePath(filePath);
            info.setFileSize(file.length());
            info.setFileName(file.getName());
            
            // 根据扩展名确定格式
            String extension = filePath.substring(filePath.lastIndexOf('.') + 1).toLowerCase();
            info.setFormat(extension);
            
            return info;
            
        } catch (Exception e) {
            log.error("获取音频文件信息失败", e);
            return null;
        }
    }

    /**
     * 音频文件信息类
     */
    public static class AudioFileInfo {
        private String filePath;
        private String fileName;
        private String format;
        private long fileSize;

        // Getters and Setters
        public String getFilePath() { return filePath; }
        public void setFilePath(String filePath) { this.filePath = filePath; }
        
        public String getFileName() { return fileName; }
        public void setFileName(String fileName) { this.fileName = fileName; }
        
        public String getFormat() { return format; }
        public void setFormat(String format) { this.format = format; }
        
        public long getFileSize() { return fileSize; }
        public void setFileSize(long fileSize) { this.fileSize = fileSize; }

        @Override
        public String toString() {
            return String.format("AudioFileInfo{fileName='%s', format='%s', size=%d bytes}", 
                fileName, format, fileSize);
        }
    }
}
